package notsafeToSafe;

import java.util.concurrent.locks.ReentrantLock;

public class Window implements Runnable {
    private static int tickets = 100;

    // 1.创建Lock的实例，需要确保多个线程共用同一个Lock实例
    private static final ReentrantLock LOCK = new ReentrantLock();

    @Override
    public void run() {

    }


    // 同步方法  默认同步监视器为 this
    public synchronized void saleTickets(int num) {
        if (tickets >= num) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            tickets -= num;
            System.out.println(Thread.currentThread().getName() + ": 取票成功！成功购买 " + num + " 张票。剩余: " + tickets);
        } else {
            System.out.println(Thread.currentThread().getName() + ": 余票不足！仅剩 " + tickets + " 张票。");
        }
    }

    public void saleTickets() {
        // 结构：Class clz = Window.class (是一个对象，加载到内存中的这个类)
        synchronized (Window.class) {
            if (tickets >= 1) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                tickets--;
                System.out.println(Thread.currentThread().getName() + ": 取票成功！成功购买 " + 1 + " 张票。剩余: " + tickets);
            } else {
                System.out.println(Thread.currentThread().getName() + ": 余票不足！仅剩 " + tickets + " 张票。");
            }
        }
    }

    public void saleTicket() {
        // 2. 执行lock方法，锁定对共享资源的调用
        LOCK.lock();
        try {
            if (tickets >= 1) {
                Thread.sleep(10);
                tickets--;
                System.out.println(Thread.currentThread().getName() + ": 取票成功！成功购买 " + 1 + " 张票。剩余: " + tickets);
            } else {
                System.out.println(Thread.currentThread().getName() + ": 余票不足！仅剩 " + tickets + " 张票。");
            }


        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 3.释放对共享资源的锁定
            LOCK.unlock();
        }

    }
}
